/*
 * @lc app=leetcode.cn id=998 lang=typescript
 *
 * [998] 最大二叉树 II
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function insertIntoMaxTree(root: TreeNode | null, val: number): TreeNode | null {
  let parentNode: TreeNode | null = null;
  let currNode = root;
  while (currNode) {
    if (val > currNode.val) {
      if (!parentNode) {
        return new TreeNode(val, root);
      }
      const node = new TreeNode(val, currNode);
      parentNode.right = node;
      return root;
    } else {
      parentNode = currNode;
      currNode = currNode.right;
    }
  }
  parentNode!.right = new TreeNode(val);
  return root;
}
// @lc code=end
